package com.ics.cmsadmin.modules.agent.steward;

import com.ics.cmsadmin.modules.agent.bean.AgentDaySummaryBean;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jsoup.helper.DataUtil;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public final class AgentUtils {

    public static List<AgentDaySummaryBean> optimizeResult(List<AgentDaySummaryBean> agentDaySummaryBeans, String startTime, String endTime) {
        if (CollectionUtils.isEmpty(agentDaySummaryBeans)) {
            agentDaySummaryBeans = new ArrayList<>();
        }
        Map<String, AgentDaySummaryBean> map = new HashMap<>();
        for (AgentDaySummaryBean item : agentDaySummaryBeans) {
            map.put(item.getSummaryDay(), item);
        }
        Date startDate = null;
        Date endDate = null;
        try {
            if (StringUtils.isBlank(startTime)) {
                startDate = DateUtils.parseDate(agentDaySummaryBeans.get(0).getSummaryDay(), "YYYY-MM-dd");
            }else {
                startDate = DateUtils.parseDate(startTime, "YYYY-MM-dd");
            }
        }catch (Exception e){
            startDate = DateUtils.addDays(new Date(), -7);
        }

        try {
            if (StringUtils.isBlank(endTime)) {
                endDate = DateUtils.parseDate(agentDaySummaryBeans.get(agentDaySummaryBeans.size() - 1).getSummaryDay(), "YYYY-MM-dd");
            }else {
                endDate = DateUtils.parseDate(endTime, "YYYY-MM-dd");
            }
        }catch (Exception e){
            endDate = DateUtils.addDays(new Date(), -1);
        }


        long diffTime = (endDate.getTime() - startDate.getTime()) / 1000 / 3600 / 24;
        Date finalStartDate = startDate;
        return Stream.iterate(0, n -> n + 1)
            .limit(diffTime + 1)
            .map(item -> {
                    String format = DateFormatUtils.format(DateUtils.addDays(finalStartDate, item), "YYYY-MM-dd");
                    return Optional.ofNullable(map.get(format))
                        .orElse(AgentDaySummaryBean.builder().summaryDay(format).build());
                }
            ).collect(Collectors.toList());
    }

    public static List<AgentDaySummaryBean> optimizeResult() {
        return optimizeResult(null, null, null);
    }
}
